package com.xianyun.site.iblog.gatewayimpl;

import com.alibaba.fastjson.JSONObject;
import com.xianyun.common.core.utils.FormatUtils;
import com.xianyun.site.iblog.convertor.SystemUserConvertor;
import com.xianyun.site.iblog.domain.user.gateway.SystemUserGateway;
import com.xianyun.site.iblog.domain.user.model.SystemUser;
import com.xianyun.site.iblog.gatewayimpl.database.SystemUserMapper;
import com.xianyun.site.iblog.gatewayimpl.database.domainobject.SystemUserDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author mac_zyj
 */
@Slf4j
@Component
public class SystemUserGatewayImpl implements SystemUserGateway {

    @Autowired
    private SystemUserMapper systemUserMapper;


    @Autowired
    private RocketMQTemplate rocketMq;

    @Override
    public void registerUser(SystemUser systemUser) {
        SystemUserDO systemUserDO = SystemUserConvertor.toDataObjectForCreate(systemUser);
        String transactionId = FormatUtils.getTransactionId();
        //构建消息体
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(systemUserDO);
        jsonObject.put("System_User",systemUserDO);
        Message<String> message = MessageBuilder.withPayload(jsonObject.toJSONString())
                .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId).build();
        TransactionSendResult sendResult = rocketMq.sendMessageInTransaction("register_user_message", message, null);
        log.info("send transactional message body={},result={}",message.getPayload(),sendResult.getSendStatus());
    }

    @Override
    public Integer getUserIdByUserUniquePath(String userUniquePath) {
        return systemUserMapper.getUserIdByUserUniquePath(userUniquePath);
    }
}
